import type { HoldItem } from '@/indexDB/initHold'
import type { HoldHistoryItem } from '@/indexDB/initHistory'

import { useList } from '@/hooks/useList'
import dayjs from 'dayjs'


export const useHistory = () => {
  const { list, handleAdd, handleEdit } = useList<HoldHistoryItem>({
    'listKey': 'historyList'
  })

  const getAim = (activeHoldItem: HoldItem) => {
    let aim: 'add' | 'edit' = 'add'
    let activeHistoryList: HoldHistoryItem[] = [] // 当前持仓项的历史
    let beforeItem = {} as HoldHistoryItem
    const { id } = activeHoldItem
    if (!list.value?.length) {
      activeHistoryList = []
    } else {
      activeHistoryList = list.value.filter(each => each.holdId === id)
    }

    if (!activeHistoryList?.length) {
      aim = 'add'
    } else {
      beforeItem = [...activeHistoryList].pop() as HoldHistoryItem
      const { updateTime } = beforeItem
      const updateDay = dayjs(+updateTime).format('YYYY-MM-DD')
      const today = dayjs().format('YYYY-MM-DD')
      if (updateDay === today) {
        // 更新
        aim = 'edit'
      } else {
        aim = 'add'
      }
    }
    return {
      aim,
      beforeItem,
      activeHistoryList
    }
  }

  const handleHistory = (activeHoldItem: HoldItem) => {
    const { id, holdNum, holdEarnings, holdEarningsPercent, holdPrice, holdValue, latestPrice } = activeHoldItem
    const { aim, beforeItem, activeHistoryList } = getAim(activeHoldItem)
    const data: HoldHistoryItem = {
      holdId: id,
      createTime: '',
      updateTime: new Date().getTime() + '',
      latestPrice,
      holdNum,
      holdPrice,
      holdValue, // 持仓市值
      holdEarnings, // 持仓收益
      holdEarningsPercent // 持仓收益率,百分比
    }
    const { updateTime } = data
    if (!activeHistoryList?.length) {
      data.createTime = updateTime
      handleAdd(data)

    } else {
      if (aim === 'add') {
        data.createTime = data.updateTime
        handleAdd(data)
      } else {
        const { createTime, id } = beforeItem
        handleEdit({
          ...data,
          createTime: createTime || new Date().getTime() + '',
          id,
        })
      }
    }
  }
  return {
    list,
    handleHistory
  }
}